package cn.tianya.irock.util;

import java.util.List;

import org.apache.commons.lang.StringUtils;

public class Formatter {
	
	public static String checkStringLength(String stringToCheck, int maxLength) {
		String checkedString = null;

		if (stringToCheck.length() <= maxLength)
			return stringToCheck;

		if ((stringToCheck.length() > maxLength) && (stringToCheck.indexOf(" ") == -1)) {
			checkedString = stringToCheck.substring(0, maxLength) + "...";
		} else if (stringToCheck.length() > 0) {
			checkedString = stringToCheck.substring(0, maxLength) + "...";
		} else {
			checkedString = stringToCheck;
		}

		return checkedString;
	}
			
	public static String toDelimitedString(List<String> strs, String delimiter) {
		StringBuilder buf = new StringBuilder();
		int size = strs.size();
		
		for (int idx = 0; idx < strs.size() - 2; idx++) {
			buf.append(strs.get(idx).toString() + delimiter);
		}
		
		if (size > 0) {
			buf.append(strs.get(size - 1).toString() + delimiter);
		}
		return buf.toString();

	}
	
	public static String highLightHtml(String str, String word, int start, int len) {
		int end;
		String temp;

		if (start < 0) {
			throw new ArrayIndexOutOfBoundsException();
		}
		start = str.indexOf(word);
		start -= word.length() << 1;
		if (start < 0) {
			start = 0;
		}
		end = start + len + word.length();
		if (end > str.length()) {
			end = str.length() - 1;
		}
		temp = highLightHtml(str.substring(start, end), word);
		return temp;
	}
	
	public static String highLightHtml(String str, String word) {
		String[] words = null;
		
		words = word.split(" ");
		word = StringUtils.join(words, "|");
		return str.replaceAll(word, "<em class=\"Label\">$0</em>");
	}
	
	public static String highLightHtml(String str, List<String> words) { 
		String temp = toDelimitedString(words, "|");
		return str.replaceAll(temp, "<em class=\"Label\">$0</em>");
	}
}
